/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bsd5ex.group1.kaokang.dao;

import com.bsd5ex.group1.kaokang.dbUtil.HibernateUtil;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author VAIO
 */
public abstract class AbstractDAO<T> {
    
    protected Session session = null;
    
    public AbstractDAO() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
    
    public T getByID(int id) {
        Transaction tx = session.beginTransaction();
        Object result = session.createQuery("from "+getEntityName()+" where id_"+getEntityName().toLowerCase()+" = "+id)
                .uniqueResult();
        return (T)result;
    }
    
    public List<T> listAll() {
        List<T> list = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery ("from "+getEntityName());
            list = (List<T>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public List<T> query(String query) {
        List<T> list = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery ( query );
            list = (List<T>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public Object queryOneResult(String query){
        Object object = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery ( query );
            object =  q.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
    
    public void delete(T object) {
        Transaction tx = session.beginTransaction();
        session.delete( object );
        tx.commit();
    }
    
    public void saveOrUpdate(T object) {
        Transaction tx = session.beginTransaction();
        session.saveOrUpdate( object );
        tx.commit();
    }
    
    public void save(T object) {
        Transaction tx = session.beginTransaction();
        session.save( object );
        session.refresh(object);
        tx.commit();
    }
    
    public String getEntityName(){
        return ((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getSimpleName();
    };
}
